import os
import logging
from weasyprint import HTML, CSS
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import requests
from PIL import Image
import io

logger = logging.getLogger(__name__)

class PDFConverter:
    """PDF转换服务类"""
    
    def __init__(self):
        """初始化PDF转换服务"""
        self.temp_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'data', 'temp')
        os.makedirs(self.temp_dir, exist_ok=True)
        
    def convert_html_to_pdf(self, html_content, output_path):
        """
        将HTML内容转换为PDF
        
        Args:
            html_content: HTML内容
            output_path: 输出PDF路径
            
        Returns:
            str: PDF文件路径
        """
        try:
            # 处理HTML内容
            processed_html = self._process_html_content(html_content)
            
            # 创建HTML对象
            html = HTML(string=processed_html)
            
            # 定义CSS样式
            css = CSS(string='''
                @page {
                    margin: 2cm;
                    @top-center {
                        content: string(title);
                    }
                    @bottom-center {
                        content: counter(page);
                    }
                }
                body {
                    font-family: "Microsoft YaHei", "SimSun", sans-serif;
                    line-height: 1.6;
                    color: #333;
                }
                h1 {
                    font-size: 24px;
                    color: #2c3e50;
                    margin-bottom: 20px;
                }
                p {
                    margin-bottom: 1em;
                }
                img {
                    max-width: 100%;
                    height: auto;
                    margin: 10px 0;
                }
                a {
                    color: #007bff;
                    text-decoration: none;
                }
                .article-meta {
                    color: #666;
                    font-size: 14px;
                    margin-bottom: 20px;
                }
            ''')
            
            # 生成PDF
            html.write_pdf(output_path, stylesheets=[css])
            
            return output_path
            
        except Exception as e:
            logger.error(f"转换PDF失败: {str(e)}")
            return None
            
    def _process_html_content(self, html_content):
        """
        处理HTML内容
        
        Args:
            html_content: 原始HTML内容
            
        Returns:
            str: 处理后的HTML内容
        """
        try:
            # 解析HTML
            soup = BeautifulSoup(html_content, 'html.parser')
            
            # 处理图片
            for img in soup.find_all('img'):
                if img.get('src'):
                    # 下载图片
                    img_data = self._download_image(img['src'])
                    if img_data:
                        # 转换为base64
                        img['src'] = f"data:image/jpeg;base64,{img_data}"
                        
            # 处理视频
            for video in soup.find_all('video'):
                video.decompose()  # 移除视频标签
                
            # 处理链接
            for link in soup.find_all('a'):
                if link.get('href'):
                    link['target'] = '_blank'
                    
            return str(soup)
            
        except Exception as e:
            logger.error(f"处理HTML内容失败: {str(e)}")
            return html_content
            
    def _download_image(self, url):
        """
        下载图片
        
        Args:
            url: 图片URL
            
        Returns:
            str: base64编码的图片数据
        """
        try:
            # 发送请求下载图片
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                # 打开图片
                img = Image.open(io.BytesIO(response.content))
                
                # 转换为JPEG格式
                if img.format != 'JPEG':
                    img = img.convert('RGB')
                    
                # 保存为JPEG
                output = io.BytesIO()
                img.save(output, format='JPEG', quality=85)
                
                # 转换为base64
                import base64
                return base64.b64encode(output.getvalue()).decode()
                
            return None
            
        except Exception as e:
            logger.error(f"下载图片失败: {str(e)}")
            return None
            
    def batch_convert(self, html_files, output_dir):
        """
        批量转换HTML文件为PDF
        
        Args:
            html_files: HTML文件列表
            output_dir: 输出目录
            
        Returns:
            list: 生成的PDF文件列表
        """
        try:
            pdf_files = []
            
            for html_file in html_files:
                try:
                    # 读取HTML内容
                    with open(html_file, 'r', encoding='utf-8') as f:
                        html_content = f.read()
                        
                    # 生成输出文件名
                    output_filename = os.path.splitext(os.path.basename(html_file))[0] + '.pdf'
                    output_path = os.path.join(output_dir, output_filename)
                    
                    # 转换PDF
                    pdf_path = self.convert_html_to_pdf(html_content, output_path)
                    if pdf_path:
                        pdf_files.append(pdf_path)
                        
                except Exception as e:
                    logger.error(f"转换文件失败 {html_file}: {str(e)}")
                    continue
                    
            return pdf_files
            
        except Exception as e:
            logger.error(f"批量转换失败: {str(e)}")
            return [] 